package com.monitor.app_monitor.service.quartz.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPathException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
@Service
public class RgExecuteScript {

    @Resource
    @Qualifier("dataAnalysisThreadPool")
    private ThreadPoolExecutor threadPoolExecutor;


    public RgEmsInfo executeScript(String script) throws Exception {
        final String scriptPath = script;
        final boolean exists = new File(scriptPath).exists();
        if (!exists) {
            log.error("脚本不存在");
            throw new ScriptNotExistsException();
        }
        String command = "bash";
        //数据文件存储路径

        StringBuilder commandStr = new StringBuilder();
        commandStr.append(scriptPath);
//                .append(" ")
//                .append(scriptPath);
        final String finallyCommand =commandStr.toString();
        log.info("开始执行脚本 =>{}", finallyCommand);
        final Process process = Runtime.getRuntime().exec(finallyCommand);

        final Future<RgEmsInfo> successResult =
                this.threadPoolExecutor.submit((Callable<RgEmsInfo>) () -> {
                    final StringBuilder resultInfo = new StringBuilder();
                    try (
                            InputStream inputStream = process.getInputStream();
                    ) {
                        final byte[] buffer = new byte[1024 * 8];
                        int len = 0;
                        while ((len = inputStream.read(buffer)) > 0) {
                            resultInfo.append(new String(buffer, 0, len));
                        }
                        final String result = resultInfo.toString();
                        return JSON.parseObject(result, RgEmsInfo.class);
                    } catch (JSONPathException e) {
                        log.error("解析脚本返回结果失败 script=>{}", commandStr);
                    }
                    return RgEmsInfo.errorResult();
                });

        final Future<RgEmsInfo> errorResult =
                this.threadPoolExecutor.submit((Callable<RgEmsInfo>) () -> {
                    StringBuilder errorInfo = new StringBuilder();

                    try (
                            InputStream errorStream = process.getErrorStream()
                    ) {
                        final byte[] buffer = new byte[1024 * 8];
                        int len = 0;
                        while ((len = errorStream.read(buffer)) > 0) {
                            errorInfo.append(new String(buffer, 0, len));
                        }
                        final StringBuilder error = errorInfo;
                        log.info("读取错误信息=>{}", error);
                    } catch (Exception e) {
                        log.error("执行脚本错误 errorResult=>{}", script);
                    }
                    return RgEmsInfo.errorResult();
                });

        //等待执行完成
        process.waitFor();
        //获取返回数据
        try {
            final RgEmsInfo scriptExecResult = successResult.get();
            //log.info("脚本执行完成,返回结果=>{}", scriptExecResult);
            return scriptExecResult;
        } catch (Exception e) {
            final RgEmsInfo scriptExecResult = errorResult.get();
            return scriptExecResult;
        } finally {
            process.destroy();
        }

    }


}
